<!-- CertificateEdit 培训修改 -->
<template>
  <div class="content">
    <el-form v-loading="formLoading" class="page-form" :model="data" :rules="rules" ref="paperForm" size="medium"
      label-width="140px">
      <el-form-item label="培训名称：" prop="title">
        <el-input class="page-form-item" v-model="data.title" placeholder="请输入培训名称（不得超过30字）" maxlength="30"></el-input>
      </el-form-item>
      <el-form-item label="考试费用：" prop="price">
        <el-input class="page-form-item" v-model="data.price">
          <div slot="append">元</div>
        </el-input>
      </el-form-item>
      <el-form-item label="考核达标分值：" prop="passedScore">
        <el-input class="page-form-item" v-model="data.passedScore">
          <div slot="append">分</div>
        </el-input>
        <div class="form-tips">达标分值一定要小于所添加试卷中最小的总分分值</div>
      </el-form-item>
      <el-form-item label="报考次数：" prop="chance">
        <el-input class="page-form-item" v-model="data.chance">
          <div slot="append">次</div>
        </el-input>
      </el-form-item>

      <el-form-item label="可免费考试次数：" prop="freeTimes">
        <el-input class="page-form-item" v-model="data.freeTimes">
          <div slot="append">次</div>
        </el-input>
        <div class="form-tips">0次不可免考</div>
      </el-form-item>
      <el-form-item label="学习截止周期：" prop="learningHours">
        <el-input class="page-form-item" v-model="data.learningHours">
          <div slot="append">小时</div>
        </el-input>
      </el-form-item>
      <el-form-item label="考试时长：" prop="useTime">
        <el-input class="page-form-item" v-model="data.useTime">
          <div slot="append">秒</div>
        </el-input>
      </el-form-item>
      <el-form-item label="到期弹窗：" prop="expireAppDialog">
        <el-input class="page-form-item" v-model="data.expireAppDialog">
          <div slot="append">秒</div>
        </el-input>
        <div class="form-tips">默认0秒App不弹窗</div>
      </el-form-item>
      <el-form-item label="过期弹窗：" prop="expiredAppDialog">
        <el-input class="page-form-item" v-model="data.expiredAppDialog">
          <div slot="append">秒</div>
        </el-input>
        <div class="form-tips">默认0秒App不弹窗</div>
      </el-form-item>
      <el-form-item label="封面图：" prop="pic">
        <Upload v-model="data.pic" :limit="1" :fileLists="data.pic ? [data.pic]: []"></Upload>
      </el-form-item>

      <el-form-item label="是否上架：" prop="status">
        <el-radio-group v-model="data.status">
          <el-radio :label="'1'">是</el-radio>
          <el-radio :label="'0'">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="达标方式：" prop="courseType">
        <el-radio-group v-model="data.courseType">
          <el-radio v-for="(item, index) in certificateTypeList" :key="index" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="data.courseType === '2'" label="考核要求：" prop="courseScore" style="color:rgb(96, 98, 102);">
        累计学习达到
        <el-input style="width: 100px;" v-model="data.courseScore"></el-input>
        积分可以参加考核，每完成一门课程积1分
      </el-form-item>

      <el-form-item label="必学课程：" prop="courseIds">
        <el-input class="hidden-input" v-model="data.courseIds" placeholder=""></el-input>
        <div v-if="selectCourseList && selectCourseList.length <= 0" style="color:rgb(96, 98, 102);">未选择课程</div>
        <div v-else class="topics" style="color:rgb(96, 98, 102);">
          <div v-for="(item, index) in selectCourseList" :key="item.id">
            <div class="topic-title" style="color:rgb(0, 0, 0);">
              {{index + 1 + "、"}}{{item.title}} &nbsp;&nbsp;
              <el-button size="mini" type="danger" @click="onRemoveCouse(index)">删除</el-button>
            </div>
          </div>
        </div>
        <el-button type="primary" size="mini" @click="onAddCourse">添加课程</el-button>
      </el-form-item>
      <el-form-item label="试卷：" prop="paperIds">
        <el-input class="hidden-input" v-model="data.paperIds" placeholder=""></el-input>
        <div v-if="selectCourseList && selectPaperList.length <= 0" style="color:rgb(96, 98, 102);">未选择试卷</div>
        <div v-else style="color:rgb(96, 98, 102);">
          <div v-for="(item, index) in selectPaperList" :key="item.id">
            <div class="topic-title" style="color:rgb(0, 0, 0);">
              {{index + 1 + "、"}}{{item.title}} &nbsp;&nbsp;
            </div>
            <div>
              <span style="margin-right: 50px;">题数：{{item.topicCount}}</span>
              <span style="margin-right: 50px;">总分：{{item.maxScore}}</span>
              <span style="margin-right: 50px;">权重：
                <el-input @input="onProbabilityChange($event, item, index)" :value="item.probability" style="width: 70px;"
                  size="small"></el-input> %
              </span>
              <el-button size="mini" type="danger" @click="onRemovePaper(index)">删除</el-button>
            </div>
          </div>
          <div style="color:#E6A23C">
            <!-- 试卷不得超过10套， -->
            各试卷权重和为100%
          </div>
        </div>

        <el-button type="primary" size="mini" @click="onAddPaper">添加试卷</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleResetForm('paperForm')">返 回</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSubmitForm('paperForm')">保 存</el-button>
      </el-form-item>
    </el-form>

    <!-- 选择课程 -->
    <el-dialog title="选择课程" :visible.sync="courseDialog.mVisible" class="dialog-form" width="800px">

      <div style="margin-bottom:20px;font-size:16px;font-web">
        已选试卷：<span style="font-weight: bold;margin-right: 80px;">{{ courseDialog.courseCount}}</span>
        时长：<span style="font-weight: bold;">{{ courseDialog.times}}</span>
      </div>
      <el-table :data="courseDialog.tableList" v-loading="courseDialog.tableLoading" ref="dialogCourseTableData" border
        fit @selection-change="onCourseSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="课程名称" align="center" min-width="200"></el-table-column>
        <el-table-column prop="type" label="课程类型" align="center">
          <template slot-scope="scope">
            {{dealStr(scope.row.type, 'courseTypeList')}}
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="课程时长" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            {{dealStr(scope.row.status, 'courseStatusList')}}
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer" style="text-align: center;display: block;">
        <el-button size="medium" @click="courseDialog.mVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="handleCourseDiaSub('dialogCourseTableData')">确
          定</el-button>
      </span>

    </el-dialog>
    <!-- 选择课程 -->

    <!-- 选择试卷 -->
    <el-dialog title="选择试卷" :visible.sync="paperDialog.mVisible" class="dialog-form" width="800px">

      <div style="margin-bottom:20px;font-size:16px;font-web">
        已选试卷：<span style="font-weight: bold;">{{ paperDialog.paperCount}}</span>
      </div>

      <el-table :data="paperDialog.tableList" v-loading="paperDialog.tableLoading" ref="dialogPaperTableData" border
        fit @selection-change="onPaperSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="试卷名称" align="center"></el-table-column>
        <el-table-column prop="topicCount" label="题数" align="center"></el-table-column>
        <el-table-column prop="maxScore" label="分值" align="center"></el-table-column>
        <!-- <el-table-column prop="title" label="关联培训" align="center"></el-table-column> -->
      </el-table>
      <Pagination @pageChange="getPage" :pageDefultData="{
        pageNum: paperDialog.pageNum,
        pageRow: paperDialog.pageSize,
        totalCount: paperDialog.totalCount }">
      </Pagination>
      <span slot="footer" class="dialog-footer" style="text-align: center;display: block;">
        <el-button size="medium" @click="paperDialog.mVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="handlePaperDiaSub('dialogPaperTableData')">确
          定</el-button>
      </span>
    </el-dialog>
    <!-- 选择试卷 -->
  </div>
</template>

<script>
import { CertificateFormRules } from '@/utils/rules'
import { GetCourseListWithoutPage, GetPaperListWithoutPage, UpdateCertificate, GetCertificatePapersDetail } from '@/api/train'
import { ExportList } from '@/utils'
import Upload from '@/components/Upload/edit'
export default {
  name: 'CertificateEdit',
  components: { Upload },
  data () {
    return {
      courseTypeList: ExportList('courseTypeList'),
      courseStatusList: ExportList('courseStatusList'),
      certificateTypeList: ExportList('certificateTypeList'),
      btnLoading: false,
      formLoading: false,
      certificateId: '',
      data: {
        id: '',
        title: '',
        price: '',
        passedScore: '',
        chance: '',
        pic: '',
        learningHours: '',
        freeTimes: '',
        useTime: '',
        status: '',
        courseIds: '',
        paperIds: '',
        expireAppDialog: '0',
        expiredAppDialog: '0',
        courseType: '', // 达标方式
        courseScore: '' // 达标积分
      },
      rules: CertificateFormRules,
      selectCourseList: [],
      selectPaperList: [],
      courseDialog: {
        mVisible: false,
        tableList: [],
        selectTableList: [],
        totalCount: 0,
        tableLoading: false,
        courseCount: 0,
        times: 0
      },
      paperDialog: {
        mVisible: false,
        tableList: [],
        selectTableList: [],
        totalCount: 0,
        tableLoading: false,
        paperCount: 0
      },
      query: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  props: {},
  watch: {},
  computed: {},
  mounted () {
    this.certificateId = this.$route.query.id
    this.getDetail()
  },
  methods: {
    // 表单提交
    handleSubmitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        let params = {
          id: this.data.id || this.certificateId,
          title: this.data.title,
          passedScore: this.data.passedScore,
          price: this.data.price,
          chance: this.data.chance,
          pic: this.data.pic,
          learningHours: this.data.learningHours,
          freeTimes: this.data.freeTimes,
          useTime: this.data.useTime,
          status: this.data.status,
          expireAppDialog: this.data.expireAppDialog,
          expiredAppDialog: this.data.expiredAppDialog,
          courseIds: [],
          paperIds: []
        }
        if (params.courseType === '2') { // 指定积分
          params.courseScore = this.data.courseScore
        } else {
          params.courseScore = ''
        }
        // popupTime (string, optional): 弹窗时间 0不弹 ；分割 ,
        params.popupTime = this.data.expireAppDialog ? this.data.expireAppDialog : '0'
        params.popupTime += this.data.expiredAppDialog ? `;${this.data.expiredAppDialog}` : ';0'
        // 课程
        if (this.selectCourseList.length <= 0) {
          this.$message.warning('请选择课程')
          return
        }
        this.selectCourseList.forEach((item, index) => {
          const info = { id: item.id, sort: index + 1 }
          params.courseIds.push(info)
        })

        // 试卷
        if (this.selectPaperList.length <= 0) {
          this.$message.warning('请选择试卷')
          return
        }
        // if (this.selectPaperList.length >= 10) {
        //   this.$message.warning('最多10套试卷')
        //   return
        // }
        let probabilitySum = 0 // 权重和
        this.selectPaperList.forEach((item, index) => {
          let probability = item.probability
          if (typeof item.probability !== 'number') {
            probability = parseFloat(item.probability)
          }
          probabilitySum += probability
          const info = {
            id: item.id, probability: probability, sort: index + 1
          }
          params.paperIds.push(info)
        })
        if (probabilitySum !== 100) {
          this.$message.warning('试卷权重分布不正确')
          return
        }

        this.doEditCertificate(params)
      })
    },
    // 表单返回
    handleResetForm (formName) {
      this.$router.go(-1)
    },
    // 打开选择课程 dialog
    onAddCourse () {
      this.courseDialog.mVisible = true
      if (this.courseDialog.tableList.length <= 0) {
        this.getCourse()
      }
    },
    // 课程 表格select
    onCourseSelectionChange (selection) {
      this.courseDialog.selectCourseList = selection
      this.courseDialog.courseCount = this.courseDialog.selectCourseList.length
      this.courseDialog.times = 0
      selection.forEach(item => {
        this.courseDialog.times += item.useTime
      })
    },
    // 课程 dialog弹窗提交
    handleCourseDiaSub () {
      this.data.courseIds = '1'
      const selectCourseIds = this.selectCourseList ? this.selectCourseList.map(item => item.id) : []
      this.courseDialog.selectCourseList.forEach(item => {
        if (selectCourseIds.indexOf(item.id) === -1) {
          this.selectCourseList.push(item)
        }
      })
      this.courseDialog.mVisible = false
    },
    // 选择的课程 删除
    onRemoveCouse (index) {
      this.selectCourseList.splice(index, 1)
    },

    // 打开选择试卷 dialog
    onAddPaper () {
      this.paperDialog.mVisible = true
      this.getPaper()
    },
    // 试卷 表格select
    onPaperSelectionChange (selection) {
      selection.forEach(item => {
        item.probability = 0
      })
      this.paperDialog.selectPaperList = selection
      this.paperDialog.paperCount = this.paperDialog.selectPaperList.length
    },
    // 试卷 dialog 提交
    handlePaperDiaSub () {
      this.data.paperIds = '1'
      const selectPaperIds = this.selectPaperList.map(item => item.id)
      this.paperDialog.selectPaperList.forEach(item => {
        if (selectPaperIds.indexOf(item.id) === -1) {
          this.selectPaperList.push(item)
        }
      })
      this.paperDialog.mVisible = false
    },
    // 试卷删除
    onRemovePaper (index) {
      this.selectPaperList.splice(index, 1)
    },
    // 权重change
    onProbabilityChange (event, item, index) {
      item.probability = event
      this.selectPaperList.splice(index, 1, item)
    },
    // 分页处理
    getPage (val) {
      this.query.pageNum = val.pageNum
      this.query.pageSize = val.pageRow
      this.getPaper()
    },
    // 表格数据对应处理
    dealStr (key, listKey) {
      const arr = this[listKey]
      let str = ''
      arr.forEach(e => {
        const valueNumber = parseInt(e.value)
        if (e.value === key || valueNumber === key) {
          str = e.label
        }
      })
      return str
    },
    // 获取培训下 信息 试卷 课程
    getDetail () {
      this.formLoading = true
      GetCertificatePapersDetail(this.certificateId).then(res => {
        this.formLoading = false
        const data = res.data
        const examinationData = data.examination
        for (const key in this.data) {
          if (this.data.hasOwnProperty(key)) {
            if (key === 'status') {
              this.data[key] = examinationData[key].toString()
            } else {
              this.data[key] = examinationData[key]
            }
          }
        }
        this.data.courseType = examinationData.courseType ? examinationData.courseType.toString() : ''
        this.data.courseScore = examinationData.courseScore || ''

        const popupTimeList = examinationData.popupTime.split(';')
        this.data.expireAppDialog = popupTimeList[0] || '0'
        this.data.expiredAppDialog = popupTimeList[1] || '0'

        this.data.courseIds = '1'
        this.data.paperIds = '1'
        this.selectCourseList = data.courses || []
        // 权重关联
        let probabilityMap = {}
        data.paperRelations.forEach(item => {
          const key = `paperId_${item.paperId}`
          probabilityMap[key] = item.probability
        })
        data.papers.forEach(item => {
          const key = `paperId_${item.id}`
          item.probability = probabilityMap[key] || ''
        })
        this.selectPaperList = data.papers
      }).catch(e => {
        this.formLoading = false
      })
    },
    // api - 获取课程数据
    getCourse () {
      this.courseDialog.tableLoading = true
      GetCourseListWithoutPage().then(res => {
        this.courseDialog.tableLoading = false
        const data = res.data
        this.courseDialog.tableList = data.list
      }).catch(e => {
        this.courseDialog.tableLoading = false
      })
    },
    // api - 获取试卷数据
    getPaper () {
      this.paperDialog.tableLoading = true
      let params = { pageNum: this.query.pageNum, pageSize: this.pageSize }
      GetPaperListWithoutPage(params).then(res => {
        this.paperDialog.tableLoading = false
        const data = res.data
        this.paperDialog.tableList = data.list
        this.paperDialog.totalCount = data.total
      }).catch(e => {
        this.paperDialog.tableLoading = false
      })
    },
    // api - 修改培训
    doEditCertificate (params) {
      this.btnLoading = true
      UpdateCertificate(params).then(res => {
        this.$message.success(res.message || '修改成功')
        setTimeout(() => {
          this.btnLoading = false
          this.$router.go(-1)
        }, 500)
      }).catch(e => {
        this.btnLoading = false
      })
    }

  }
}

</script>
<style lang='scss' scoped>
</style>
